//参数的获取
var categoryId = GetQueryString('categoryId'),
	cityId = GetQueryString('cityId'),
	detailsUrl = '/jiadianqingxi/v1/category/'+categoryId,
	timeUrl = '/jiadianqingxi/v1/category/'+categoryId+'/service-time',
	orderUrl = '/jiadianqingxi/v1/order',
	regUrl = '/basis/v1/sms/auth_code',
	loginUrl = '/auth/saas/login',
	searchOrderUrl = '/order/queryOrderLiteById';
//全局变量
var yearScroll = '',
	hourScroll = '',
	yearNum = '',
	hourNum = '',
	Teltext = '',
//	categoryId = '',
	goodsnum = 1,
	priceSum = '',
	priceSligen = '',
	yearIndex = '',
	hourIndex = '',
	yearTextStr = '',
	hourTextStr = '',
	isIscroll = true,
	way = '',
	qrImg = '',
	myDateStr = '',
	regNumber = '',
	loginToken = '';

	goodsMes();//商品信息加载
	//商品信息加载
	function goodsMes(){
		var cusUrl = locationUrl + detailsUrl;
		var sendData = {
			channel : Channel,
			cityId : cityId
		};
		var type = 'GET' ;
		var opts = {
			'noMsg': true,
			success:function(data){
				console.log(data);
				var data = data.data;
				priceSum = data.price *goodsnum;
				priceSligen = data.price;
				var goodsStr = '';
					goodsStr ='<div class="goodsPic"><img src=" '+data.categoryIcon+' "/></div>'
						+'<div class="goodsTitle">'+data.categoryName+'</div>'
						+'<div class="goodsPrice">￥'+data.price+'</div>'
						+'<div class="goodsSum">'+goodsnum+'</div>'
						+'<div class="goodsPriceSum">￥'+priceSum+'</div>';
				$('.goodsMain').append(goodsStr);
			}
		}
		KJin.ajax(cusUrl, sendData, opts,type);
	}
	
	//当本地有用户电话----
	$(function(){
		if(localStorage.usertoken && localStorage.userphone){
			$('.LoginWrap').hide();
			Teltext = localStorage.userphone;
			$('#orderTel').val(Teltext);
			$('.regBtn').addClass('regBtnOk');
		}else if($('#orderTel').val()){
			Teltext = $('#orderTel').val();
			$('.regBtn').addClass('regBtnOk');
		}else{
			$('.LoginWrap').show();
		}
	})
		
//手机号登录
	var reg = /^1[34578]\d{9}$/;
	$('.LoginTel input').on('keyup',function(){
		Teltext = $(this).val();
		if(Teltext != '' && reg.test(Teltext)){
			$('#orderTel').val(Teltext);
//			sessionStorage.userTel = Teltext;
			$('.regBtn').addClass('regBtnOk');
		}
	})

	//点击获取验证码------
	$('.regBtn').on('click',function(){
		//当前页面刷新------
		if(Teltext != '' && reg.test(Teltext)){
//			clickRegbtn();
			var $that = $(this);
			$that.css('backgroundColor','#e4e4e4');
			$('.butMeng').show();
			var n = 60;
			function goTime(){
				n--;
				$that.text(n+'秒后');//console.log(n)
				if(n == 0){console.log(n)
					clearInterval(timer);
					$('.butMeng').hide();
					$that.text('获取验证');
					$that.css('backgroundColor','#a42b2a')
					n = 60;
				}
			}
			getRegtext();
			var timer = setInterval(goTime,1000);
		};
	});
	
	//点击获取手机验证码--------
	function getRegtext(){
		var cusUrl = locationUrl + regUrl;
		var sendData = {
			phone : Teltext
		};
		var type = 'GET';
		var opts = {
			'noMsg': true,
			headers : {
				'Cache-Control': 'no-cache'
			},
			success:function(data){
				var data = data.data;
				//regNumber = data.authCode;
				if(data.authCode){
					console.log(data.authCode);
				}
			}
		};
		KJin.ajax(cusUrl, sendData, opts,type);
	}
	//点击登录-----------------
	$('.LoginBtn').on('click',function(){
		if(Teltext != '' && reg.test(Teltext) && $('.LoginReg input').val() != ''){
			regNumber = $('.LoginReg input').val();
			getLoading();//$('.LoginWrap').hide();
			localStorage.usertoken = loginToken;
			localStorage.userphone = Teltext;
		}else{
//			alert('您的信息/验证码不正确');
			publicAlert.showAlert('您的信息/验证码不正确');
		}
	})
	//获取登录许可-------------
	function getLoading(){
		console.log(regNumber)
		var cusUrl = locationUrl + loginUrl;
		var sendData = {
			phone : Teltext
		};
		var type = 'POST';
		var opts = {
			'noMsg': true,
			headers : {
				'content-type': 'aplication/x-www-form-urlencoded',
				'Cache-Control': 'no-cache'
			},
			beforeSend: function(xhr) {
			    xhr.setRequestHeader("code",regNumber);
			},
			success:function(data){
				console.log(data);
				if(data.code == 0){
					$('#orderTel').val(Teltext);
					loginToken = data.data.token;
//					localStorage.usertoken = data.data.token;
//					localStorage.userphone = Teltext;
					$('.LoginWrap').hide();
				}else{
//					alert('验证码错误');
					publicAlert.showAlert('验证码错误');
				}
				
			}
		}
		KJin.ajax(cusUrl, sendData, opts, type);
	}
	
//点击关闭登录
	$('.Login').on('click','.closeBtn',function(){
		window.history.go(-1);
	})


//商品信息的数量加减
	//点击减少商品--------
	$('.goShop').on('click','span:nth-child(1)',function(){//alert('ds')
		var Sdown = parseInt($(this).next().val());console.log(Sdown);
		if(Sdown == 1){
			$(this).css('color','#ddd')
			Sdown = 1;
		}else{
			Sdown--;
		}
		$(this).next().val(Sdown);
		//同时商品信息里的数量同变
		changePrice(Sdown);
	})
	//点击增加商品--------
	$('.goShop').on('click','span:nth-child(3)',function(){
		var Sup = parseInt($(this).prev().val());console.log(Sup);
		Sup++;
		$(this).prev().val(Sup);
		$('.goShop').children('span').eq(0).css('color','#333');
		//同时商品信息里的数量同变
		changePrice(Sup);
		
	})
	//通过上面的数量总价变动-----
	function changePrice(goodsnums){
		goodsnum = goodsnums;
		priceSum = goodsnum*priceSligen;
		$('.goodsSum').html(goodsnum);
		$('.goodsPriceSum').html('￥'+priceSum);
	}
	
//点击选择日期
	//滑动配置项-----
	$('#picktime').on('click',function(){
//		$('.dateWrap').show();
		$('#showDiv').show();
		timeData();
		yearScroll.refresh();
		dataScroll.refresh();
	})
	$('.dateMeng').on('click',function(){
		$('#showDiv').hide();
	})
	$('.dateBtn_no').on('click',function(){
		$('#showDiv').hide();
	})
	//事件数据的请求加载--------
	function timeData(){
		var cusUrl = locationUrl + timeUrl;
		var sendData = {
			channel : Channel,
			cityId : cityId,
			count : goodsnum,
			longitude :localStorage.pointlng,//localStorage.pointlng?localStorage.pointlng:'121.48789949',
			latitude :localStorage.pointlat// localStorage.pointlat?localStorage.pointlat:'31.24916171'
		};
		var type = 'POST' ;
		var opts = {
			'noMsg': true,
			success:function(data){
				console.log(data);
				var data = data.data,yearStru = '',hourStru = '',
					len = data.length;
				for(var i = 0;i<len ;i++){
					yearStru +='<li index = '+i+'>'+data[i].date+'</li>';
					for(var n = 0;n<data[i].time.length;n++){
							if(data[i].time[n] != 'undefined'){
								hourStru +='<li>'+data[0].time[n]+'</li>';
							}
						}
				}
				$('#yearBase').after(yearStru);
				$('#timerBase').after(hourStru);
				yearScroll.refresh();
				dataScroll.refresh();
				yearTextStr = $('#yearWrapper ul').children('li').eq(1).html();
				hourTextStr = $('#dateWrapper ul').children('li').eq(1).html();
				yearScroll.scrollTo(0,0);
				dataScroll.scrollTo(0,0);
			}
		}
		KJin.ajax(cusUrl, sendData, opts,type);
	}
	//每次选择年月日后都会重新请求------------
    	var yearScroll = new IScroll('#yearWrapper',{
    		click:true,
    		tap:true,
    	})
    	var dataScroll = new IScroll('#dateWrapper',{
    		click:true,
    		tap:true,
    	})
    	yearScroll.on('scrollEnd',function(){
//  		console.log(yearScroll.scrollerHeight);
//  		console.log(yearScroll.y);
    		var nowIndex =Math.abs(Math.round(yearScroll.y/40));
    		console.log(nowIndex);
    		var key= nowIndex+1;console.log(key);
    		yearIndex = key +1;
    		yearTextStr = $('#yearWrapper li:nth-child('+ yearIndex +')').html();
    		hourTextStr = $('#dateWrapper ul').children('li').eq(hourIndex).html();
    		yearScroll.scrollToElement(document.querySelector('#yearWrapper li:nth-child('+ key +')'));
    		hourTextStr = $('#dateWrapper ul').children('li').eq(1).html();
    		//加载对应的时间日期中的组件
    		timeComponent(yearTextStr);
    	})
    	$("#yearWrapper li").on("click",function(e){
//  		console.log(e);
    		var that = $(this);alert(that)
    		console.log(that.index());
    		
    	});
    	
    	dataScroll.on('scrollEnd',function(e){
    		var nowIndex =Math.abs(Math.round(dataScroll.y/40));
    		console.log(nowIndex);
    		++nowIndex;
    		var nowIndexof = nowIndex +1;
    		hourIndex = nowIndexof;
    		hourTextStr = $('#dateWrapper li:nth-child('+ nowIndexof +')').html();
    		dataScroll.scrollToElement(document.querySelector('#dateWrapper li:nth-child('+ nowIndex +')'));
    	})
    	
    	$("#dateWrapper li").on("click",function(e){
//  		console.log(e);
    		var that = $(this);
    		console.log(that.index());
    		
    	})
    	
    	function timeComponent(key){
    		//绘制时间里面的数据添加到 dateWrapper中
    		//这里使用的是 $("#timerBase").after()
    		var cusUrl = locationUrl + timeUrl;
			var sendData = {
				channel : Channel,
				cityId : cityId,
				count : goodsnum,
				longitude :localStorage.pointlng,//localStorage.pointlng?localStorage.pointlng:'121.48789949',
				latitude :localStorage.pointlat// localStorage.pointlat?localStorage.pointlat:'31.24916171'
			};
			var type = 'POST' ;
			var opts = {
				'noMsg': true,
				success:function(data){
					console.log(data);
					var data = data.data,yearStru = '',hourStru = '',
						len = data.length;
					for(var i = 0;i<len ;i++){
						if(yearTextStr == data[i].date){
							$('.dateUr').html('');
							for(var n = 0;n<data[i].time.length;n++){
								
								hourStru +='<li>'+data[i].time[n]+'</li>';
							}
						}	
					}
					$('#timerBase').after(hourStru);
					dataScroll.refresh();
				}
			}
			KJin.ajax(cusUrl, sendData, opts,type);
	    		
	    		
    	}
    	
    	if(document.addEventListener){
    		document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    	}else{//兼容IE
    		document.attachEvent('ontouchmove', function (e) { 
    			var e = window.event;
    			e.preventDefault(); }, false);
    	}
    
		//点击确定选定日期------
		//当点击确定之后选定时间
		$('.dateBtn').on('click','.dateBtn_ok',function(){
			$('#picktime').val(yearTextStr+' '+hourTextStr);
			$('#showDiv').hide();
		})
		//点击蒙版----------
		$('#showDiv').on('click','.dateMeng',function(){
			$('#showDiv').hide();
		})
		
	

//点击支付
	var nameMes = '',phoneMes = '',adressMes = '';
	$('.orderWrap').on('click','.gofukuan',function(){
		
		if($('#orderName').val() && $('#orderTel').val() && reg.test($('#orderTel').val()) && $('#orderAdrr').val() && $('#picktime').val()){
			$('.payWrap').show();
			nameMes = $('#orderName').val();
			phoneMes = $('#orderTel').val();
			adressMes = $('#orderAdrr').val();
//			chooseWay();  //此处改逻辑
			creatOrder();
			
		}else{
			$('.payWrap').hide();
			publicAlert.showAlert('您的信息不能为空！');
//			alert('您的信息不能为空！')
		}
		
		//点击关闭支付--------
//		$('.payClose').unbind('click');  
		$('.payClose').on('click',function(){console.log('dsf')
			$('.payWrap').hide();
			$('.payMain').hide();
		})
	})
	
	$('.payOkBtn').on('click','.payOkBtn_left',function(){
		way = 'alipay_qr' ;console.log(way)
		var tpsStr = '请使用支付宝扫描二维码支付';
		$('.payTips').html(tpsStr);
		$('.payOkWrap').hide();
		$('.payMain').show();
//		creatOrder();
		ordergoPay();
	});
	
	$('.payOkBtn').on('click','.payOkBtn_right',function(){
		way = 'wx_pub_qr' ;
		var tpsStr = '请使用微信扫描二维码支付';
		$('.payTips').html(tpsStr);
		$('.payOkWrap').hide();console.log(way)
		$('.payMain').show();
//		creatOrder();
		ordergoPay();
	})
	//选择支付方式
	function chooseWay(){
		$('.payOkWrap').show();
		
	}
	//创建订单-----------
	var subjectName ='',ordertype = '',payPrice = '',ourId = '',bodyData = '';
	function creatOrder(){
		var cusUrl = locationUrl + orderUrl;
		var sendData = {
			channel : Channel,
			customerUserId:'blm_test',
			userPhone : Teltext,
			cityId : cityId,
			categoryId : categoryId,
			count : goodsnum,
			serviceTime : yearTextStr+' '+ hourTextStr,
			contact :{
				name : nameMes,
				phone : phoneMes,
				address : adressMes,
				longitude :localStorage.pointlng,//localStorage.pointlng?localStorage.pointlng:'121.48789949',
				latitude :localStorage.pointlat// localStorage.pointlat?localStorage.pointlat:'31.24916171'
			} ,
			couponId : '',
			activityId :''
		};
		sendData.customerId = 261;
		sendData.appCode = 'jhdp';
		var type = 'POST' ;
		var opts = {
			'noMsg': true,
			headers : {
				'token': localStorage.usertoken
			},
			success:function(data){
				console.log(data);
				var data = data.data;
				subjectName = data.name;
				ordertype = data.orderType;
				payPrice = data.price;
				ourId = data.id;
				bodyData = data.date;
				chooseWay();
				getNowDate();
//				ordergoPay();
			}
		}
		KJin.ajax(cusUrl, sendData, opts,type);

	}
	//下单成功后调取支付----
	function ordergoPay(){
		var cusUrl = locationUrl+"/payment/v1/charge";
		var sendData = {
			amount : payPrice *100 ,
			id : ourId,
			channel : way,
			orderType : ordertype,
			subject : subjectName,
			body :subjectName + bodyData
			
		};
		var type = 'POST' ;
		if(way === 'wx_pub_qr'){
			sendData.extra = {
				product_id :ourId
			}
		}
		var opts = {
			'noMsg': true,
			success:function(reply){
				console.log(reply)
				if(reply.code === 0) {
					var charge = reply.data;
					var credential = charge. credential;
					console.log(charge. credential);
					qrImg = 'http://pan.baidu.com/share/qrcode?w=198&h=198&url=' + encodeURIComponent(credential.alipay_qr || credential.wx_pub_qr);
					 $('.payPic img').attr('src', qrImg);
					setTimeout(pingChange,5000);
				}	
			}
		}	
		KJin.ajax(cusUrl, sendData, opts,type);
}

	function pingChange(){
		var cusUrl = locationUrl + searchOrderUrl;
		var sendData = {
			id : ourId 
		};
		var type = 'POST';
		var opts = {
			'noMsg': true,
			success: function(data){
				console.log(data);
				var status =data.data.status;
				console.log(data.status);
				if(status == 2){
//					pingChange();//overPaySuc();//测试用的
					setTimeout(pingChange,15000);
				}else if(status == 3 || status == 9 || status == 11){
					overPaySuc();
				}
			}
		};
		KJin.ajax(cusUrl, sendData, opts,type);
	}
	
//获取时间——下单时间
	function getNowDate(){
		var mydate = new Date();
		var year = mydate.getFullYear();
		var month = mydate.getMonth()+1;
		var day = mydate.getDate();
		var hour = mydate.getHours();
		var minute = mydate.getMinutes();
		var second = mydate.getSeconds();
			myDateStr = year+'-'+month+'-'+day+'  '+hour+':'+minute//+':'+second;
	}
//overPaySuc();测试用的
//支付成功之后
	function overPaySuc(){
		$('.payMain').hide();
		$('.overPayWrap').show();
		setTimeout(function(){
			$('.overPayWrap').hide();
		},3000)
//		$('.overPayWrap').show();
		$('.orderMes').hide();
		$('.orderTime').hide();
		$('.gofukuan').hide();
		$('.payOrderMain_wrap').show();
		$('.payOrder_tnow').text(myDateStr);
		$('.payOrder_t').text(yearTextStr+' '+hourTextStr);
		$('.payOrder_d').text(ourId);
		$('.payOrder_n').text(nameMes);
		$('.payOrder_tel').text(phoneMes);
		$('.payOrder_addr').text(adressMes);
//		$('.payClose').unbind('click');  
		$('.payClose').on('click',function(){
			$('.payWrap').hide();
			var k = 10;
			var tipsStr = '';
			tipsStr = '<div id="goBack">'+ k +'秒后跳转~~</div>';
//			$('.orderWrap').append(tipsStr);
			if(k == 0){
				k = 10;
			}else{
				setInterval(function(){
					tipsStr = '<div id="goBack">'+ k +'秒后跳转~~</div>';
					k--;
					$('#goBack').html(tipsStr);
					if(k == 0){
						window.location.href = '../index.html';
						k = 10;
					}
				},1000);	
				
			}
		})
	}
	
//解决IScroll 滑动式出现卡壳现象
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);